package com.j4.core;

import com.google.common.collect.Lists;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionManager;
import org.mybatis.guice.XMLMyBatisModule;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;

import java.util.List;

public class Init {
	
	private static final Injector injector;
	static {
		List<Module> modules = Lists.newArrayList();
		modules.add(new XMLMyBatisModule() {
			@Override
			protected void initialize() {
				setEnvironmentId("j4");
				setClassPathResource("sqlMapConfig.xml");
			}
		});
		injector = Guice.createInjector(modules);
        initMapper(injector.getInstance(SqlSessionManager.class));
    }

    /**
     * 初始化通用 Mapper，如果想要支持参数，可以增加配置文件，读取 Properties
     *
     * @param sqlSessionManager
     */
    private static void initMapper(SqlSessionManager sqlSessionManager){
        SqlSession sqlSession = sqlSessionManager.openSession();
        MapperHelper mapperHelper = new MapperHelper();
        mapperHelper.registerMapper(Mapper.class);
        mapperHelper.processConfiguration(sqlSession.getConfiguration());
        sqlSession.close();
    }

	public static Injector getInjector() {
		return injector;
	}
}
